$(function() {
    $("body").i18n();
    window.relayout = function() {
        $("#adviceListGrid").datagrid("resize", {
            width : 1,
            height : 1
        });
        var p = $("#adviceListGrid").datagrid("getPanel").closest('td');
        var w = p.width();
        var h = p.height();
        $("#adviceListGrid").datagrid("resize", {
            width : w,
            height : h
        });
        $("#picListGrid").datagrid("resize", {
            width : 1,
            height : 1
        });
        var p2 = $("#picListGrid").datagrid("getPanel").closest('td');
        var w2 = p2.width();
        var h2 = p2.height();
        $("#picListGrid").datagrid("resize", {
            width : w2,
            height : h2
        });
    }
    
    $(window).resize(function() {
        setTimeout("relayout()", 100);
    });
    
    $("#picFileInput").filebox({
        buttonText : $.i18n.get('batchHandler.btn.select'),
        buttonAlign : 'left',
        onChange : function(filePath, oldVal) {
            var allowedExtensions = "jpg,bmp,png,gif";
            var idx = filePath.lastIndexOf('.');
            var valid = false;
            if (idx != -1) {
                valid = true;
            }
            if (valid) {
                var extension = filePath.substring(idx + 1);
                valid = (allowedExtensions.indexOf(extension.toLowerCase()) != -1);
            }
            if (!valid) {
                $.messager.alert($.i18n.get('error'), $.i18n.get("accessory.file.extension.err") + allowedExtensions, 'error', function() {
                    $('#picUploadForm').form('reset');
                });
            }
        }
    })
    $('#picUploadForm').form({
        onSubmit : function(param) {
            if ($("#picFileInput").filebox('getValue') == '') {
                $.messager.alert($.i18n.get('error'), $.i18n.get("accessory.upload.needfile"), 'error')
                return false;
            }
            $.messager.progress({
                title : $.i18n.get('prompt'),
                msg : $.i18n.get('waitingMessage')
            });
            return true;
        },
        success : function(data) {
            $.messager.progress('close');
            var resp = $.parseJSON(data);
            if (resp.success !== undefined && resp.success === false) {
                $.messager.alert($.i18n.get('error'), resp.msg || $.i18n.get("prompt.connection.exception"), 'error');
            } else {
                $.messager.alert($.i18n.get('prompt'), $.i18n.get("saveSuccess"), 'info', function() {
                    $('#picUploadForm').form('reset');
                    onSearchPicList();
                });
            }
        }
    });
    window.onUploadPic = function() {
        $('#picUploadForm').form('submit');
    }
    $("#picListGrid").datagrid({
        toolbar : '#picListGrid-toolbar',
        url : contextPath + '/sample/findPageByPictureShow.pvt',
        pagination : true,
        pageSize : 10,
        rownumbers : true,
        striped : true,
        singleSelect : false,
        idField : 'id',
        nowrap : false,
        pagePosition : 'bottom',
        totalProperty : "total",
        rowsProperty : "pics",
        fitColumns : true,
        frozenColumns : [[{
            field : 'id',
            checkbox : true
        }]],
        columns : [[{
            field : 'name',
            width : 300,
            title : $.i18n.get('pictureShow.name')
        }]]
    });
    window.onSearchPicList = function() {
        $('#picListGrid').datagrid('clearSelections').datagrid('load', {})
    }
    window.onDelPicList = function() {
        var selectedRow = getSelectedRow('#picListGrid', true);
        if (selectedRow) {
            $.messager.confirm($.i18n.get('prompt'), $.i18n.get('confirmDeleteData'), function(result) {
                if (result) {
                    var ids = [];
                    $(selectedRow).each(function() {
                        ids.push(this.id);
                    });
                    $.messager.progress({
                        title : $.i18n.get('prompt'),
                        msg : $.i18n.get('waitingMessage')
                    });
                    $.ajax({
                        url : contextPath + '/sample/deletePictureShows.pvt',
                        data : {
                            ids : ids.join(",")
                        },
                        type : "post",
                        success : function(resp) {
                            $.messager.progress('close');
                            if (resp.success == true) {
                                onSearchPicList();
                            } else {
                                $.messager.alert($.i18n.get('error'), resp.msg, 'error');
                            }
                        },
                        error : function(xhr, status, error) {
                            $.messager.progress('close');
                            $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
                        }
                    });
                }
            });
        }
    }
    $("#adviceFileInput").filebox({
        buttonText : $.i18n.get('batchHandler.btn.select'),
        buttonAlign : 'left',
        onChange : function(filePath, oldVal) {
            var allowedExtensions = "xls";
            var idx = filePath.lastIndexOf('.');
            var valid = false;
            if (idx != -1) {
                valid = true;
            }
            if (valid) {
                var extension = filePath.substring(idx + 1);
                valid = (allowedExtensions.indexOf(extension.toLowerCase()) != -1);
            }
            if (!valid) {
                $.messager.alert($.i18n.get('error'), $.i18n.get("accessory.file.extension.err") + allowedExtensions, 'error', function() {
                    $('#adviceUploadForm').form('reset');
                });
            }
        }
    })
    
    window.onDownloadAdviceTpl = function() {
        doExport(contextPath + "/sample/downloadBatchAddTpl.pvt");
    }
    
    function doExport(url) {
        $.messager.progress({
            title : $.i18n.get('prompt'),
            msg : $.i18n.get('sample5.export.tip')
        });
        var id = "_download_hidden_frame_";
        $("#" + id).remove();
        var frame = $("<iframe id=" + id + "></iframe>").appendTo("body");
        frame.css({
            position : "absolute",
            display : "none",
            top : -1000,
            left : -1000,
            width : 0,
            height : 0
        });
        //2秒后关闭，以免重复点击
        setTimeout(function() {
            $.messager.progress('close');
        }, 2000);
        frame.attr("src", url);
    }
    
    $("#adviceListGrid").datagrid({
        toolbar : '#adviceListGrid-toolbar',
        url : contextPath + '/sample/findPageByAdvice.pvt',
        pagination : true,
        pageSize : 10,
        rownumbers : true,
        striped : true,
        singleSelect : false,
        idField : 'id',
        nowrap : false,
        pagePosition : 'bottom',
        totalProperty : "total",
        rowsProperty : "advices",
        fitColumns : true,
        frozenColumns : [[{
            field : 'id',
            checkbox : true
        }]],
        columns : [[{
            field : 'type',
            width : 90,
            title : $.i18n.get('advice.type'),
            formatter : function(value, row, index) {
                if (value == '1') {
                    return $.i18n.get("advice.type.1");
                }
                if (value == '2') {
                    return $.i18n.get("advice.type.2");
                }
                return value;
            }
        }, {
            field : 'info',
            width : 250,
            title : $.i18n.get('advice.info')
        }]]
    });
    
    window.onSearchAdvice = function() {
        $('#adviceListGrid').datagrid('clearSelections').datagrid('load', {})
    }
    
    $('#adviceUploadForm').form({
        onSubmit : function(param) {
            if ($("#adviceFileInput").filebox('getValue') == '') {
                $.messager.alert($.i18n.get('error'), $.i18n.get("accessory.upload.needfile"), 'error')
                return false;
            }
            $.messager.progress({
                title : $.i18n.get('prompt'),
                msg : $.i18n.get('waitingMessage')
            });
            return true;
        },
        success : function(data) {
            $.messager.progress('close');
            var resp = $.parseJSON(data);
            if (resp.success !== undefined && resp.success === false) {
                $.messager.alert($.i18n.get('error'), resp.msg || $.i18n.get("prompt.connection.exception"), 'error');
            } else {
                var dealRs = resp.batchDealResult;
                var info;
                if (dealRs != null && dealRs.length > 0) {
                    info = '';
                    for (var i = 0; i < dealRs.length; i++) {
                        if (info != '')
                            info += "<br>";
                        info += $.i18n.get("batchHandler.grid.errrow") + " : " + dealRs[i].errorRowIndex + " " + 
                        $.i18n.get("batchHandler.grid.errinfo") + " : " + dealRs[i].errorInfo + ";";
                    }
                } else {
                    info = $.i18n.get("saveSuccess");
                }
                $.messager.alert($.i18n.get('prompt'), info, 'info', function() {
                    $('#adviceUploadForm').form('reset');
                    onSearchAdvice();
                });
            }
        }
    });
    
    window.onUploadAdvice = function() {
        $('#adviceUploadForm').form('submit');
    }
    window.onDelAdvice = function() {
        var selectedRow = getSelectedRow('#adviceListGrid', true);
        if (selectedRow) {
            $.messager.confirm($.i18n.get('prompt'), $.i18n.get('confirmDeleteData'), function(result) {
                if (result) {
                    var ids = [];
                    $(selectedRow).each(function() {
                        ids.push(this.id);
                    });
                    $.messager.progress({
                        title : $.i18n.get('prompt'),
                        msg : $.i18n.get('waitingMessage')
                    });
                    $.ajax({
                        url : contextPath + '/sample/deleteAdvices.pvt',
                        data : {
                            ids : ids.join(",")
                        },
                        type : "post",
                        success : function(resp) {
                            $.messager.progress('close');
                            if (resp.success == true) {
                                onSearchAdvice();
                            } else {
                                $.messager.alert($.i18n.get('error'), resp.msg, 'error');
                            }
                        },
                        error : function(xhr, status, error) {
                            $.messager.progress('close');
                            $.messager.alert($.i18n.get('error'), error || $.i18n.get("prompt.connection.exception"), 'error');
                        }
                    });
                }
            });
        }
    }
    window.onExportAdvice = function(){
        doExport(contextPath + "/sample/exportAdvices.pvt");
    }
    
    window.downloadFailedCallback = function(msg){
        $.messager.progress('close');
        $.messager.alert($.i18n.get('error'), msg, 'error');
    }
    
    function getSelectedRow(selector, multiple) {
        var selectedRows = $(selector).datagrid('getSelections');
        if (selectedRows.length == 0) {
            showPromptMsg($.i18n.get('selectMinOneRecord'));
            return false;
        } else if (!multiple && selectedRows.length > 1) {
            showPromptMsg($.i18n.get('selectOneRecord'));
            return false;
        } else {
            return multiple ? selectedRows : selectedRows[0];
        }
    }
    function showPromptMsg(msg) {
        $.messager.alert($.i18n.get('prompt'), msg, 'warning');
    }
});